package com.bwie.bargain.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.bwie.bargain.conf.AlipayConfig;
import com.bwie.bargain.conf.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.bwie.bargain.entity.BarorderEntity;
import com.bwie.bargain.service.BarorderService;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author ShuangzhiZhao
 * @email 466505908@qq.com
 * @date 2022-03-13 19:25:33
 */
@RestController
@RequestMapping("bargain/barorder")
public class BarorderController {
    @Autowired
    private BarorderService barorderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = barorderService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{oid}")
    public R info(@PathVariable("oid") Long oid){
		BarorderEntity barorder = barorderService.getById(oid);

        return R.ok().put("barorder", barorder);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody BarorderEntity barorder){
		barorderService.save(barorder);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BarorderEntity barorder){
		barorderService.updateById(barorder);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] oids){
		barorderService.removeByIds(Arrays.asList(oids));

        return R.ok();
    }
    /**
     * 回显前台订单页面 去支付
     */
    @RequestMapping("/info/{userId}/{activityId}")
    @ResponseBody
    public R info(@PathVariable("userId") Long userId,
                  @PathVariable("activityId")Long activityId){
        BarorderEntity order = barorderService.getByUidAid(userId,activityId);

        return R.ok().put("order", order);
    }

    /**
     * 生成订砍价单
     */
    @RequestMapping("/{pathId}/ptAdd")
    @ResponseBody
    public R ptAdd(HttpServletRequest request,
                   @PathVariable("pathId")String pathId,
                   @RequestParam("userId")Long userId,
                   @RequestParam("activityId")Long activityId,
                   @RequestParam("goodsId")Long goodsId
    ) {

        //去缓存中查询 接口地址
        String path = (String) redisTemplate.boundHashOps("path").get(goodsId + "pathId");
        //如果缓存中有，并且传入的地址和缓存中一样则生成订单
        if (StringUtils.isNotEmpty(path)&& path.equals(pathId)) {
            return barorderService.ptAdd(userId, activityId);
        } else {
            return R.error("非法请求");
        }
    }
    //生成砍价分享链接
    @RequestMapping("/generateLinks/{oid}")
    @ResponseBody
    public R generateLinks(
            @PathVariable("oid")Long oid,
            HttpServletRequest request
    ){
        //获取头部信息
        String token = request.getHeader("token");
        if (token!=null){
            Claims claims = jwtUtil.parseJWT(token);
            if (claims!=null&&"user".equals(claims.get("roles"))){
                String path = jwtUtil.createJWT(claims.getId(), oid + "", "user2");
                String links="http://localhost:88/api/bargain/barorder/visitLinks/"+path;
                return R.ok().put("links",links);
            }
            return R.error("用户未登录");
        }
        return R.error("用户未登录");

    }
    //砍价/{userId}
    @RequestMapping("/visitLinks/{path}/{oid}")
    @ResponseBody
    public R visitLinks(@PathVariable("path") String path,
//                        @PathVariable("userId")Long userId,
                        @PathVariable("oid")String oid,
                        HttpServletRequest request){
        //判断登录者
        String token = request.getHeader("token");//获取头部信息
        if (token!=null){
            Claims claims = jwtUtil.parseJWT(token);//解析
            if (claims!=null&&"user".equals(claims.get("roles"))){
                String userId = claims.getId();

                //判断活动者
                Claims claims2 = jwtUtil.parseJWT(path);
                if (claims2!=null&&"user2".equals(claims2.get("roles"))){
                    if (!claims2.getId().equals(userId)){
                        if (claims2.getSubject().equals(oid)){
                            return barorderService.bargain(Long.parseLong(userId),claims2.getId(),Long.parseLong(oid));
                        }else {
                            return R.error("活动不匹配");
                        }
                    }else {
                        return R.error("不能为自己砍价");
                    }
                }
                    return R.error("砍价链接有误");
            }
            return R.error("请先登录");
        }
        return R.error("请先登录");

    }


    //支付
    @RequestMapping("/payment")
    @ResponseBody
    public String payment(@RequestParam Long oid) throws Exception {
        BarorderEntity orderEntity = barorderService.getById(oid);


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderEntity.getOrderno().getBytes(),"UTF-8");
        //付款金额，必填
        String total_amount = new String(orderEntity.getGoodsPrice().toString().getBytes(),"UTF-8");
        //订单名称，必填
        String subject = new String(orderEntity.getGoodsName().getBytes(),"UTF-8");
        //商品描述，可空
        String body = new String(orderEntity.getGoodsName().getBytes(),"UTF-8");
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //输出
        return result;
    }

    @RequestMapping("/success.html")
    public String success(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        R r=barorderService.updateOder(params);
        if (r.getCode()==0){
            return "redirect:http://127.0.0.1:5500/bargain_list.html";
        }


        return "error";

    }

}
